package com.photography.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 设置允许的源，使用前端开发服务器的地址
        corsConfiguration.addAllowedOrigin("http://localhost:5173");  // Vite 默认端口
//        corsConfiguration.addAllowedOrigin("http://47.107.171.173");
        // 允许携带认证信息
        corsConfiguration.setAllowCredentials(true);

        // 允许的请求头
        corsConfiguration.addAllowedHeader("*");

        // 允许的请求方法
        corsConfiguration.addAllowedMethod("GET");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("PUT");
        corsConfiguration.addAllowedMethod("DELETE");
        corsConfiguration.addAllowedMethod("OPTIONS");

        // 暴露的响应头
        corsConfiguration.addExposedHeader("*");

        // 预检请求的有效期，单位秒
        corsConfiguration.setMaxAge(3600L);

        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}
